package com.fleapx.netty_learn.learn_beat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.Random;


/**
 * @Author: feng peng
 * @version:: netty_heart
 * @description:
 * @create: 2021/12/3 1:14.
 */
public class HeartClient {
    int port;
    Channel channel;
    Random random;

    public HeartClient(int port) {
        this.port = port;
        this.random = new Random();
    }

    public static void main(String[] args) {
        HeartClient heartClient = new HeartClient(9061);
        heartClient.start();
    }

    private void start() {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .channel(NioSocketChannel.class)
                    .handler(new BeatInitClient());
            //连接server
            connect(bootstrap, port);
            String text = "i am client";
            while (channel.isActive()){
                sendMsg(text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            eventExecutors.shutdownGracefully();
        }

    }

    private void sendMsg(String text)throws Exception {
        channel.writeAndFlush(text);
        int num = random.nextInt(10);
        System.out.println("[client] sleep "+ num);
        Thread.sleep(num*1000);
    }

    public void connect(Bootstrap bootstrap, int port) throws Exception {
        channel = bootstrap.connect("localhost", 9061).sync().channel();
    }
}
